﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Text;
using System.Configuration;

using Wicresoft.Framework.Organization;
using Wicresoft.Busi.BizLogic;
using Wicresoft.Busi.Entity;
using System.Collections.Generic;
public partial class Car_VehicleApply : BaseAuthenticationPage
{
    
    #region Property Opener
    public string Opener
    {
        get
        {
            if (ViewState["opener"] != null)
                return ViewState["opener"].ToString();
            else
                return "";
        }
        set
        {
            ViewState["opener"] = value;
        }
    }
    #endregion

    #region Property ApplyID
    public int ApplyID
    {
        get
        {
            if (ViewState["ApplyID"] != null)
                return int.Parse(ViewState["ApplyID"].ToString());
            else
                return int.MinValue;
        }
        set
        {
            ViewState["ApplyID"] = value;
        }
    }
    #endregion

    private string ModuleID
    {
        get
        {
            return string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><value type=""System.Guid"">{0}</value>", ConfigurationManager.AppSettings["ModuleID"]);
        }
    }
    private string SendTime
    {
        get
        {
            return string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><value type=""System.DateTime"">{0}</value>", DateTime.Now);
        }
    }
    private string SenderName
    {
        get
        {
            return CurrentUser.DisplayName;
        }
    }

    public string getReceiver(string userName, string userDisplayName, string Mobile)
    {
        return string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
                                    <Receivers>
  			                                   <Receiver>
    				                                    <Name>{0}</Name>
    				                                    <DisplayName>{1}</DisplayName>
    				                                    <NodeType>User</NodeType>
    				                                    <Email></Email>
    				                                    <LCS></LCS>
    				                                    <Mobile>{2}</Mobile>
    				                                    <Fax></Fax>
  			                                    </Receiver>
                                    </Receivers>", userName, userDisplayName, Mobile);
    }

    protected void Page_Load(object sender, System.EventArgs e)
    {
 	//User[] Users = OrganizationHelper.GetUserInfoListByRole(new Guid(WebCommon.GetConfig("Car.Auditor")), true);
        //LogHelper.WriteLog("公车申请Users总数:" + Users.Length.ToString());
       
        if (!Page.IsPostBack)
        {
            
            
            
                   Department[] deptList = CurrentUser.GetDepartments();
        List<Department> otherList = new List<Department>();
        foreach (Department item in deptList)
        {
            if (item.DisplayName != "嘉定新城（马陆镇）" && item.DisplayName != "人社局" && item.DisplayName != "各街镇劳动保障所")
            {
                otherList.Add(item);
            }
        }
      
            if (otherList.Count > 0)
            {
                this.tbGroupName.Text = otherList[0].DisplayName;
            }
            else 
            {
                this.tbGroupName.Text = " 嘉定新城（马陆镇）";
            }
            
            
            
            
            
            this.tbApplicantName.Text = CurrentUser.DisplayName;
            this.txtRemark3.Text = CurrentUser.DisplayName;
            //this.tbGroupName.Text = BasePage.GetDept(CurrentUser.ID).DisplayName;
            if (Request.QueryString["opener"] != null && Request.QueryString["opener"] != "")
            {
                this.Opener = Request.QueryString["opener"];
            }

            if (Request.QueryString["ApplyID"] != null && Request.QueryString["ApplyID"] != "")
            {
                this.ApplyID = int.Parse(Request.QueryString["ApplyID"]);
                LoadApplyInfo();
                this.tdFg1.Visible = false;
                this.tdClose.Visible = false;
            }
            else
            {
                if (Request.QueryString["StartDate"] != null && Request.QueryString["StartDate"] != "")
                {
                    this.dtpStartTime.Time = DateTime.Parse(Request.QueryString["StartDate"].ToString());
                }
                else
                {
                    this.dtpStartTime.Time = DateTime.Now;
                }
                if (Request.QueryString["EndDate"] != null && Request.QueryString["EndDate"] != "")
                {
                    this.dtpEndTime.Time = DateTime.Parse(Request.QueryString["EndDate"].ToString());
                }
                else
                {
                    this.dtpEndTime.Time = DateTime.Now;
                }
            }

            DataTable dtData = Wicresoft.Common.DataAccess.ExecuteSql("Wicresoft.Framework.ConnectionString",
                   string.Format(@"Select ValueString from PropertyData where NodeID='{0}' and PropertyID in (
                    select ID from Property where Name='Mobile')", CurrentUser.ID.ToString())).Tables[0];
            string mobile = dtData.Rows.Count == 0 ? "" : dtData.Rows[0]["ValueString"].ToString();
            tbPhone.Text = mobile;
        }
    }

    #region 修改车辆申请信息时,根据申请ID,读取申请详细信息
    private void LoadApplyInfo()
    {
        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();

        this.dtpStartTime.Time = info.StartDate;
        this.dtpEndTime.Time = info.EndDate;
        this.tbRemark2.Text = info.Remark2.ToString();
        this.txtPeopCount.Text = info.PeopCount.ToString();
        this.txtPurpose.Text = info.Purpose;

        this.tbStartAddress.Text = info.StartAddress;
        this.txtDestination.Text = info.Destination;

        this.tbApplicantName.Text = CurrentUser.DisplayName;




        this.tbGroupName.Text = info.GroupName;
        this.tbPhone.Text = info.Phone;
        this.tbRemark1.Text = info.Remark1;
        if (info.Remark1 != null && info.Remark1 != "")
        {
            string[] userNames = info.Remark1.Split(';');
            StringBuilder sbUserID = new StringBuilder();
            StringBuilder sbUserDisplayName = new StringBuilder();
            foreach (string userName in userNames)
            {
                User user = OrganizationHelper.GetUserInfo(userName);
                if (user != null)
                {
                    sbUserID.Append(user.ID.ToString() + ";");
                    sbUserDisplayName.Append(user.DisplayName + ";");
                }
            }
            if (sbUserID.Length > 0)
                this.tbUserID.Text = sbUserID.ToString(0, sbUserID.Length - 1);
        }

        this.txtRemark3.Text = info.Remark3;
        this.txtNote.Text = info.Notes;

        this.cblYclx.SelectedValue = info.Yclx;

        if (info.Status != "0")
            this.tdSave.Visible = false;
        //this.btnCancel.Visible = true;
    }
    #endregion

    protected void btnReset_Click(object sender, System.EventArgs e)
    {
        if (this.ApplyID == int.MinValue)
        {
            this.dtpStartTime.Time = DateTime.Now;
            this.dtpEndTime.Time = DateTime.Now;
            this.tbRemark2.Text = string.Empty;
            this.txtPeopCount.Text = string.Empty;
            this.txtPurpose.Text = string.Empty;

            this.tbStartAddress.Text = string.Empty;
            this.txtDestination.Text = string.Empty;

            this.tbApplicantName.Text = CurrentUser.DisplayName;

            Department[] deptList = CurrentUser.GetDepartments();
            List<Department> otherList = new List<Department>();
            foreach (Department item in deptList)
            {
                if (item.DisplayName != "嘉定新城（马陆镇）")
                {
                    otherList.Add(item);
                }
            }

            if (otherList.Count > 0)
            {
                this.tbGroupName.Text = otherList[0].DisplayName;
            }
            else
            {
                this.tbGroupName.Text = " 嘉定新城（马陆镇）";
            }
            
            

            //this.tbGroupName.Text = BasePage.GetDept(CurrentUser.ID).DisplayName;

            this.tbRemark1.Text = string.Empty;
            this.tbUserID.Text = string.Empty;
            //this.tbUserDisplayName.Text = string.Empty;
            this.tbPhone.Text = string.Empty;
            this.txtRemark3.Text = string.Empty;
            this.txtNote.Text = string.Empty;
        }
        else
        {
            LoadApplyInfo();
        }
    }

    protected void lbtnSave_Click(object sender, System.EventArgs e)
    {
        int nPeopCount = 0; int nDateCount = 0;

        if (dtpStartTime.Time < DateTime.Now)
        {
            WebCommon.ShowMessage(this.Page, "开始时间应大于现在时间,请选择正确的时间.");
            return;
        }
        if (dtpEndTime.Time <= dtpStartTime.Time)
        {
            WebCommon.ShowMessage(this.Page, "开始时间应小于结束时间,请选择正确的时间.");
            return;
        }

        try
        {
            if (tbRemark2.Text != string.Empty) nDateCount = int.Parse(this.tbRemark2.Text);
        }
        catch
        {
            WebCommon.ShowMessage(this.Page, "天数必须是整数.");
            return;
        }

        try
        {
            if (txtPeopCount.Text != string.Empty) nPeopCount = int.Parse(this.txtPeopCount.Text);
        }
        catch
        {
            WebCommon.ShowMessage(this.Page, "人数必须是整数.");
            return;
        }
        if (this.tbStartAddress.Text.Trim() == "")
        {
            WebCommon.ShowMessage(this.Page, "请输入出发地.");
            return;
        }


        if (this.txtDestination.Text.Trim() == "")
        {
            WebCommon.ShowMessage(this.Page, "请输入目的地.");
            return;
        }

        if (this.txtNote.Text.Length > 500)
        {
            WebCommon.ShowMessage(this.Page, "备注长度不超过500字,请重新输入.");
            return;
        }

        if (this.ApplyID == int.MinValue)
        {
            Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2();

            info.StartDate = dtpStartTime.Time;
            info.EndDate = dtpEndTime.Time;
            info.Remark2 = nDateCount;
            info.PeopCount = nPeopCount;
            if (txtPurpose.Text != string.Empty) info.Purpose = this.txtPurpose.Text;
            info.Destination = this.txtDestination.Text;
            info.StartAddress = this.tbStartAddress.Text;

            info.Applicant = CurrentUser.Name;
            info.ApplicantName = tbApplicantName.Text.Trim();
            info.GroupID = BasePage.GetDept(CurrentUser.ID).ID;
            info.GroupName = tbGroupName.Text.Trim();

            info.Remark1 = tbRemark1.Text;
            info.Remark3 = txtRemark3.Text;
            info.Notes = txtNote.Text;

            info.ApplyDate = DateTime.Now;
            info.Status = VehicleUseStatus.POST;
            info.Yclx = this.cblYclx.SelectedValue;
            info.Phone = this.tbPhone.Text;
            info.Add();
        }
        else
        {
            Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
            info.Load();

            info.StartDate = dtpStartTime.Time;
            info.EndDate = dtpEndTime.Time;
            info.Remark2 = nDateCount;
            info.PeopCount = nPeopCount;
            info.Purpose = this.txtPurpose.Text;

            info.StartAddress = this.tbStartAddress.Text;
            info.Destination = this.txtDestination.Text;

            info.Applicant = CurrentUser.Name;
            info.ApplicantName = tbApplicantName.Text;
            info.GroupID = BasePage.GetDept(CurrentUser.ID).ID;
            info.GroupName = tbGroupName.Text.Trim();

            info.Remark1 = tbRemark1.Text;
            info.Remark3 = txtRemark3.Text;
            info.Notes = txtNote.Text;

            info.ApplyDate = DateTime.Now;
            info.Status = VehicleUseStatus.POST;
            info.Yclx = this.cblYclx.SelectedValue;
            info.Phone = this.tbPhone.Text;
            info.UpdateByPrimaryKey();
        }

        #region 发送申请提醒

        ////MsgUtil msgUtil = new MsgUtil(tbUserID.Text, tbRemark1.Text, tbUserDisplayName.Text, string.Empty);
        //StringBuilder sbTag = new StringBuilder();
        //sbTag.Append(this.txtPurpose.Text);
        //sbTag.Append(";" + dtpStartTime.Time.ToString("yyyy-MM-dd HH:mm") + "-" + dtpEndTime.Time.ToString("yyyy-MM-dd HH:mm"));
        //sbTag.Append(";" + txtNote.Text);
        ////msgUtil.SendMessage(CurrentUser.Name, string.Empty, "车辆申请：" + txtPurpose.Text, sbTag.ToString());

        //if (cbImportance.Checked)
        //{
        User[] Users = OrganizationHelper.GetUserInfoListByRole(new Guid(WebCommon.GetConfig("Car.Auditor")), true);
        LogHelper.WriteLog("公车申请Users总数:" + Users.Length.ToString());
        foreach (User user in Users)
        {
            try
            {
                //MsgUtil msgUtil = new MsgUtil(user.ID.ToString(), user.Name, user.DisplayName, string.Empty);
                //StringBuilder sbTag = new StringBuilder();
                //sbTag.Append(txtTopic.Text);
                //sbTag.Append(";" + txtDate.Text + " " + ddlStartTime.SelectedItem.Text + "-" + ddlEndTime.SelectedItem.Text);
                //sbTag.Append(";" + ddlRoom.SelectedItem.Text);
                //sbTag.Append(";" + txtNote.Text);
                string msg = "{0}应{1}于{2}至{3}日申请使用公车。";
                msg = string.Format(msg, CurrentUser.DisplayName, this.txtPurpose.Text, dtpStartTime.Time.ToString("yyyy-MM-dd HH:mm"), dtpEndTime.Time.ToString("yyyy-MM-dd HH:mm"));
                //msgUtil.SendMessage(CurrentUser.Name, string.Empty, "车辆申请：" + txtPurpose.Text, msg, msg);

                MessageService.MessagesService service = new MessageService.MessagesService();
                DataTable dtData = Wicresoft.Common.DataAccess.ExecuteSql("Wicresoft.Framework.ConnectionString",
                    string.Format(@"Select ValueString from PropertyData where NodeID='{0}' and PropertyID in (
                    select ID from Property where Name='Mobile')", user.ID.ToString())).Tables[0];
                string mobile = dtData.Rows.Count == 0 ? "" : dtData.Rows[0]["ValueString"].ToString();
                LogHelper.WriteLog("公车申请Users:" + user.DisplayName + "的手机：" + mobile);
                if (!string.IsNullOrEmpty(mobile))
                {
                    string status = service.SendMessageByModuleID(ModuleID, SenderName, getReceiver(user.Name, user.DisplayName, mobile), msg, "", false, 1, string.Empty, SendTime);

                }
            }
            catch (Exception ex) {
                LogHelper.WriteLog("公车申请报错:" + ex.Message);
            }
        }
        //}
        #endregion

        if (this.Opener.Equals("InfoList"))
            ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('保存成功');window.close();window.opener.document.location.href=window.opener.document.location.href;</script>");
        else
        {
            if (Request["ApplyID"] == null)
                WebCommon.ShowMessage(this.Page, "保存成功");
            else
                ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('保存成功');window.opener.document.location.href=window.opener.document.location.href;</script>");
        }
        this.btnReset_Click(this, e);
    }

    protected void btnCancel_Click(object sender, System.EventArgs e)
    {
        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();
        info.Status = VehicleUseStatus.CANCEL;
        info.UpdateByPrimaryKey();
        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('操作成功.');window.close();window.opener.document.location.href=window.opener.document.location.href;</script>");
    }

}
